<template>
  <el-config-provider :locale="zhCn">
    <div class="admin-layout">
      <el-container class="layout-container">
        <!-- 侧边栏 - 添加动态宽度和折叠状态类 -->
        <el-aside :width="isCollapse ? '60px' : '220px'" class="sidebar" :class="{ 'is-collapse': isCollapse }">
          <div class="logo-container">
            <div class="logo">
              <el-icon :size="28" color="#409EFF">
                <Management />
              </el-icon>
              <!-- 添加v-show控制标题显示 -->
              <h1 v-show="!isCollapse">中科通信</h1>
            </div>
          </div>

          <!-- 菜单部分保持不变 -->
          <!-- 修改el-menu组件的颜色属性 -->
          <el-menu class="el-menu-vertical" :default-active="activeMenu" :collapse="isCollapse" router
            background-color="var(--el-menu-bg-color)" text-color="var(--el-menu-text-color)"
            active-text-color="var(--el-menu-active-color)">
            <el-menu-item index="/home">
              <el-icon>
                <HomeFilled />
              </el-icon>
              <span>首页</span>
            </el-menu-item>

            <el-sub-menu index="2">
              <template #title>
                <el-icon>
                  <User />
                </el-icon>
                <span>用户管理</span>
              </template>
              <el-menu-item index="/user/list">用户列表</el-menu-item>
              <el-menu-item index="/user/roles">角色管理</el-menu-item>
              <el-menu-item index="/user/permission">权限设置</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="3">
              <template #title>
                <el-icon>
                  <Goods />
                </el-icon>
                <span>商品管理</span>
              </template>
              <el-menu-item index="/product/list">商品列表</el-menu-item>
              <el-menu-item index="/product/category">分类管理</el-menu-item>
              <el-menu-item index="/product/brand">品牌管理</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="4">
              <template #title>
                <el-icon>
                  <Tickets />
                </el-icon>
                <span>订单管理</span>
              </template>
              <el-menu-item index="/order/list">订单列表</el-menu-item>
              <el-menu-item index="/order/refund">退款处理</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="5">
              <template #title>
                <el-icon>
                  <DataAnalysis />
                </el-icon>
                <span>数据分析</span>
              </template>
              <el-menu-item index="/analysis/sales">销售统计</el-menu-item>
              <el-menu-item index="/analysis/user">用户分析</el-menu-item>
            </el-sub-menu>

            <el-menu-item index="/settings">
              <el-icon>
                <Setting />
              </el-icon>
              <span>系统设置</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <el-container>
          <!-- 顶部导航栏 -->
          <el-header class="header">
            <div class="header-left">
              <el-button :icon="isCollapse ? Expand : Fold" circle plain @click="toggleSidebar" />
              <div class="breadcrumb">
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item v-for="item in breadcrumb" :key="item.path">
                    {{ item.meta.title }}
                  </el-breadcrumb-item>
                </el-breadcrumb>
              </div>
            </div>

            <div class="header-right">
              <!-- 添加主题切换按钮 -->
              <el-tooltip content="切换主题" placement="bottom">
                <ThemeSwitch />
              </el-tooltip>

              <el-tooltip content="全屏" placement="bottom">
                <el-button :icon="FullScreen" circle plain @click="toggleFullscreen" />
              </el-tooltip>

              <el-tooltip content="消息通知" placement="bottom">
                <el-badge :value="12" class="item">
                  <el-button :icon="Bell" circle plain />
                </el-badge>
              </el-tooltip>

              <el-dropdown>
                <span class="user-info">
                  <el-avatar :size="36" :src="user.avatar" />
                  <span class="username">{{ user.name }}</span>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-icon>
                        <User />
                      </el-icon>个人中心
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-icon>
                        <Setting />
                      </el-icon>个人设置
                    </el-dropdown-item>
                    <el-dropdown-item divided @click="logout">
                      <el-icon>
                        <SwitchButton />
                      </el-icon>退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-header>

          <!-- 标签页导航 -->
          <div class="tabs-container">
            <el-tabs v-model="activeTab" type="card" closable @tab-remove="removeTab">
              <el-tab-pane v-for="tab in tabs" :key="tab.path" :name="tab.path" :label="tab.title" />
            </el-tabs>
          </div>

          <!-- 主内容区域 -->
          <el-main class="main-container">
            <router-view v-slot="{ Component }">
              <transition name="fade-transform" mode="out-in">
                <div class="transition-wrapper">
                  <component :is="Component" />
                </div>
              </transition>
            </router-view>
          </el-main>

          <!-- 页脚 -->
          <el-footer class="footer">
            © 本项目基于 node.js+Vue3 构建
          </el-footer>
        </el-container>
      </el-container>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute, type RouteLocationMatched } from 'vue-router'
import { useFullscreen } from '@vueuse/core'
import { ElConfigProvider, ElMessageBox } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import ThemeSwitch from '@/components/ThemeSwitch.vue';
import { initTheme } from '@/utils/theme';
import {
  HomeFilled,
  User,
  Goods,
  Tickets,
  DataAnalysis,
  Setting,
  Management,
  Expand,
  Fold,
  Bell,
  FullScreen,
  SwitchButton
} from '@element-plus/icons-vue'

// 用户信息
const user = ref({
  name: '管理员',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  role: '超级管理员'
})

// 侧边栏折叠状态
const isCollapse = ref(false)
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 全屏功能
const { toggle: toggleFullscreen } = useFullscreen()

// 路由相关
const router = useRouter()
const route = useRoute()

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 标签页功能
const tabs = ref([
  { title: '首页', path: '/home' }
])
const activeTab = ref('/home')

// 添加路由标签
watch(route, (newRoute) => {
  const title = newRoute.meta.title || '未命名'
  const path = newRoute.path

  // 如果标签不存在，则添加
  if (!tabs.value.some(tab => tab.path === path)) {
    tabs.value.push({ title: title as string, path: path as string })
  }

  // 激活当前标签
  activeTab.value = path
}, { immediate: true })

// 移除标签
const removeTab = (targetPath: string) => {
  if (targetPath === '/home') return // 首页不能关闭

  const tabsList = tabs.value
  let activePath = activeTab.value

  // 如果关闭的是当前激活的标签
  if (activePath === targetPath) {
    tabsList.forEach((tab, index) => {
      if (tab.path === targetPath) {
        const nextTab = tabsList[index + 1] || tabsList[index - 1]
        if (nextTab) {
          activePath = nextTab.path
        }
      }
    })
  }

  // 更新标签列表
  tabs.value = tabsList.filter(tab => tab.path !== targetPath)

  // 如果删除后没有激活的标签，则激活首页
  if (!tabs.value.some(tab => tab.path === activePath)) {
    activePath = '/home'
  }

  // 更新激活标签并跳转
  activeTab.value = activePath
  router.push(activePath)
}

// 面包屑导航
const breadcrumb = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched as RouteLocationMatched[]
})

// 退出登录功能完善
const logout = async () => {
  try {
    // 在原位置添加以下代码
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '确认退出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 清除用户信息
    user.value = {
      name: '',
      avatar: '',
      role: ''
    };

    // 清除本地存储的认证信息
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');

    // 跳转到登录页
    router.push('/login');

    // 重置标签页状态
    tabs.value = [{ title: '首页', path: '/home' }];
    activeTab.value = '/home';
  } catch (error) {
    // 用户取消操作，不执行任何操作
    return;
  }
};

// 初始化主题
initTheme();
</script>

<style lang="scss">
.admin-layout {
  height: 100vh;
  overflow: hidden;
  background-color: var(--el-bg-color);

  .layout-container {
    height: 100%;
  }

  // 侧边栏样式
  .sidebar {
    background-color: var(--el-menu-bg-color);
    transition: width 0.3s;
    height: 100vh;
    overflow: hidden;

    .logo-container {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .logo {
        display: flex;
        align-items: center;
        padding: 0 15px;
        height: 100%;
        color: var(--el-text-color-primary);
        font-size: 18px;
        font-weight: bold;
        white-space: nowrap;

        h1 {
          margin-left: 10px;
          font-size: 18px;
          transition: all 0.3s;
        }
      }
    }

    .el-menu-vertical {
      border-right: none;
      height: calc(100vh - 60px);
      overflow-y: auto;
      background-color: var(--themeColor) !important;

      &:not(.el-menu--collapse) {
        width: 220px;
      }

      // 统一菜单标题和项目样式
      .el-sub-menu__title,
      .el-menu-item {
        color: var(--el-text-color-primary) !important;
        height: 50px;
        line-height: 50px;
        margin: 5px 0;

        &:hover {
          background-color: rgba(var(--el-color-primary-rgb), 0.1) !important;
          color: var(--el-color-primary) !important;
        }

        // 修改激活状态样式，解决颜色冲突
        &.is-active {
          background-color: var(--el-color-primary) !important;
          color: white !important; // 设置白色字体以提高对比度
        }
      }

      .el-sub-menu .el-menu-item {
        height: 45px;
        line-height: 45px;
        padding-left: 50px !important;
      }
    }
  }

  // 顶部导航栏样式
  .header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    background-color: var(--el-bg-color);
    box-shadow: 0 1px 4px rgba(var(--el-border-color-rgb), 0.3);
    z-index: 9;

    .header-left {
      display: flex;
      align-items: center;

      .el-button {
        margin-right: 15px;
        --el-button-text-color: var(--el-text-color-primary);
      }

      .breadcrumb {
        font-size: 14px;
        color: var(--el-text-color-primary);
      }
    }

    .header-right {
      display: flex;
      align-items: center;

      .el-button {
        margin-left: 10px;
      }

      .user-info {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-left: 20px;

        .username {
          margin-left: 10px;
          font-size: 14px;
          color: var(--el-text-color-primary);
        }
      }

      .item {
        margin-right: 10px;
      }
    }
  }

  // 标签页容器
  .tabs-container {
    background-color: var(--el-bg-color);
    padding: 6px 10px 0;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);

    :deep(.el-tabs__header) {
      margin: 0;
    }

    :deep(.el-tabs__item) {
      height: 32px;
      line-height: 32px;
      font-size: 12px;
      padding: 0 15px !important;
      border-radius: 3px 3px 0 0 !important;
      border: 1px solid #e8eaec !important;
      margin-right: 5px;
      transition: all 0.3s;

      &.is-active {
        background-color: #1890ff;
        color: #fff;
        border-color: #1890ff !important;
      }
    }

    :deep(.el-tabs__nav-next),
    :deep(.el-tabs__nav-prev) {
      height: 32px;
      line-height: 32px;
    }
  }

  // 主内容区域
  .main-container {
    padding: 15px;
    height: calc(100vh - 120px);
    overflow: auto;
    background-color: var(--el-bg-color);
  }

  // 页脚样式
  .footer {
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 12px;
    color: var(--el-text-color-secondary);
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color);
  }

  // 页面切换动画
  .fade-transform-leave-active,
  .fade-transform-enter-active {
    transition: all 0.3s;
  }

  .fade-transform-enter-from {
    opacity: 0;
    transform: translateX(-20px);
  }

  .fade-transform-leave-to {
    opacity: 0;
    transform: translateX(20px);
  }
}
</style>

<style lang="scss">
/* 全局菜单样式重置 - 确保无过渡效果 */
.el-menu,
.el-sub-menu,
.el-menu-item,
.el-sub-menu__title {
  transition: none !important;
  animation: none !important;
}
</style>
